<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <title>axios取消请求</title>
</head>
<body>
    <div class="container">
        <button class="btn btn-primary">发送请求</button>
        <button class="btn btn-warning">取消请求</button>
    </div>

    <script>
        const btns = document.querySelectorAll('button');
        // 2. 声明全局变量
        let cancel = null;
        // 发送请求
        btns[0].onclick = function() {
            // 检测上一次请求是否已经完成
            if (cancel) {
                cancel();   // 取消上一次请求
            };
            axios({
                method: 'GET',
                url: 'http://localhost:53000/posts/2',
                // 1. 添加配置对象的属性
                cancelToken: new axios.CancelToken(function(c) {
                    // 3. 将c赋值给cancel
                    cancel: c;
                }),
            }).then(response => {
                console.log(response);
                cancel: null;
            })
        };

        // 取消请求
        btns[1].onclick = function() {
            cancel();
        };
    </script>
</body>
</html>